package com.android.lovely.ui.chat

import android.util.Log
import com.android.lovely.data.DialogueStyle
import com.android.lovely.data.RoleDialogueStyle
import com.android.lovely.data.StoreDialogueStyle
import com.android.lovely.data.UserDialogueStyle
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.manager.KVStore
import com.kotlin.extensions.json.JsonExt.toJson
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 * 聊天样式ViewModel - 负责管理和更新对话的样式设置
 * 
 * 提供对角色和用户对话样式的修改、保存和重置功能
 *
 * @author why
 * @date 2025/3/31 02:40
 */
class ChatStyleViewModel : BaseViewModel() {
    
    /**
     * 当前默认对话样式，初始化为存储的对话样式副本
     */
    public var defaultStyle: StoreDialogueStyle = KVStore.talkStyle.copy()
        private set
        

    private val _updateFlow: MutableSharedFlow<Pair<Boolean, DialogueStyle>> = MutableSharedFlow(replay = 1)
    public val updateFlow: SharedFlow<Pair<Boolean, DialogueStyle>> get() = _updateFlow

    public fun updateFontSize(fontSize: Int) {
        updateRoleStyle { this.fontSize = fontSize }
        updateUserStyle { this.fontSize = fontSize }
    }

    public fun updateRoleStyle(style: DialogueStyle.() -> Unit) {
        defaultStyle.role.apply(style)
        emitStyleUpdate(isUserStyle = false, style = defaultStyle.role)
    }

    public fun updateUserStyle(style: DialogueStyle.() -> Unit) {
        defaultStyle.user.apply(style)
        emitStyleUpdate(isUserStyle = true, style = defaultStyle.user)
    }

    public fun saveStyle() {
        Log.d("saveStyle", "saveStyle: ${defaultStyle.toJson()}")
        KVStore.talkStyle = defaultStyle
    }

    public fun resetStyle() {
        defaultStyle = StoreDialogueStyle(
            role = RoleDialogueStyle(),
            user = UserDialogueStyle()
        )
        emitStyleUpdate(isUserStyle = false, style = defaultStyle.role)
        emitStyleUpdate(isUserStyle = true, style = defaultStyle.user)
    }
    

    private fun emitStyleUpdate(isUserStyle: Boolean, style: DialogueStyle): Unit {
        _updateFlow.tryEmit(Pair(isUserStyle, style))
    }
}